import 'package:bilibili_getx/core/constant_util/size.dart';
import 'package:bilibili_getx/core/debug/debug_util.dart';
import 'package:bilibili_getx/ui/widgets/custom/rectangle_checkBox.dart';
import 'package:bilibili_getx/ui/widgets/custom/timer_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

import '../../../../../core/I18n/str_res_keys.dart';
import '../../../../../core/constant_util/app_theme.dart';
import '../../../../shared/image_asset.dart';
import 'login_logic.dart';

class BilibiliLoginView extends StatelessWidget
    with SizeConstantUtil, HYAppTheme, ImageAssets {
  static const String routeName = "/login";
  final logic = Get.find<LoginLogic>();
  final state = Get.find<LoginLogic>().state;

  BilibiliLoginView({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LoginLogic>(builder: (logic) {
      return Scaffold(
        appBar: AppBar(
          elevation: .5,
          backgroundColor: norWhite01Color,
          leading: GestureDetector(
            onTap: () {
              Get.back();
            },
            child: Icon(
              Icons.arrow_back,
              color: norTextColors,
              size: iconSizeCons.r,
            ),
          ),
          title: Text(
            state.loginTypeIsMessage
                ? SR.telRegisterAndLogin.tr.toUpperCase()
                : SR.passwordLogin.tr.toUpperCase(),
            style: TextStyle(
              fontSize: titleFontSizeCons.r,
              color: norTextColors,
              fontWeight: FontWeight.normal,
            ),
          ),
          actions: [
            ///右上角的密码登录
            GestureDetector(
              onTap: () {
                logic.changeLoginType(context);
              },
              child: Center(
                child: Container(
                  margin: EdgeInsets.only(right: 10.r),
                  child: Text(
                    state.loginTypeIsMessage
                        ? SR.passwordLogin.tr
                        : SR.telRegisterAndLogin.tr,
                    style: TextStyle(
                      fontSize: customFontSizeCons.r,
                      color: norTextColors,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
        body: Column(
          children: [
            ///2233娘背景
            buildLoginImage(),

            ///地区
            state.loginTypeIsMessage ? buildLoginRegion() : Container(),

            ///电话号码
            state.loginTypeIsMessage
                ? buildTelAndVerifyCode(context)
                : buildUserNameAndPassword(),

            ///登录按钮
            Container(
              margin: EdgeInsets.symmetric(vertical: 15.r),
              child: state.loginTypeIsMessage
                  ? buildVerifyLoginButton()
                  : buildRegisterAndLoginButton(),
            ),

            ///用户协议部分
            buildLoginAgreement(),
          ],
        ),

        ///防止键盘弹出超出边界
        resizeToAvoidBottomInset: false,
      );
    });
  }

  ///2233娘
  Widget buildLoginImage() {
    return Stack(
      children: [
        Center(
          child: Image.asset(
            bilibiliPNG,
            width: 90.r,
            height: 90.r,
          ),
        ),
        Positioned(
          width: 90.r,
          height: 90.r,
          left: 0,
          bottom: 0,
          child: Image.asset(
            state.isInputPassword ? close22PNG : open22PNG,
            gaplessPlayback: true,
          ),
        ),
        Positioned(
          width: 90.r,
          height: 90.r,
          right: 0,
          bottom: 0,
          child: Image.asset(
            state.isInputPassword ? close33PNG : open33PNG,
            gaplessPlayback: true,
          ),
        ),
      ],
    );
  }

  ///地区（+86）
  Widget buildLoginRegion() {
    return GestureDetector(
      onTap: () {
        buildRegionDialog();
      },
      child: Stack(
        children: [
          Container(
            alignment: Alignment.centerLeft,
            width: double.infinity,
            padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15).r,
            decoration: BoxDecoration(
              color: norWhite01Color,
              border: Border(
                ///底部设置边框
                bottom: BorderSide(width: 1.r, color: norWhite06Color),
              ),
            ),
            child: Text(
              state.regionList[state.regionIndex].region,
              style: TextStyle(color: norTextColors),
            ),
          ),
          Positioned(
            right: 15.r,
            top: 0,
            bottom: 0,
            child: Icon(
              Icons.arrow_forward_ios,
              size: iconSizeCons.r,
            ),
          )
        ],
      ),
    );
  }

  ///用户名和密码
  Widget buildUserNameAndPassword() {
    return Container(
      color: norWhite01Color,
      width: 1.sw,
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 15).r,
            decoration: BoxDecoration(
              color: norWhite01Color,
              border: Border(
                bottom: BorderSide(
                  width: 2.r,
                  color: norWhite06Color,
                ),
              ),
            ),
            child: Row(
              children: [
                Container(
                  alignment: Alignment.centerLeft,
                  width: 45.r,
                  child: Text(
                    SR.account.tr,
                    style: TextStyle(
                      color: norTextColors,
                      fontSize: customFontSizeCons.r,
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    margin: EdgeInsets.only(left: 15.r),
                    child: TextField(
                      focusNode: state.userNameFocusNode,
                      autofocus: true,
                      showCursor: true,
                      onChanged: (text) {
                        logic.updateUserName(text);
                      },
                      cursorColor: norMainThemeColors,
                      controller: state.userNameTextEditController,
                      decoration: InputDecoration(
                        hintText: SR.pleaseInputTelOrMail.tr,
                        border: InputBorder.none,
                        hintStyle: TextStyle(
                          fontSize: customFontSizeCons.r,
                          fontFamily: bF,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      style: TextStyle(
                        fontSize: customFontSizeCons.r,
                        color: norMainThemeColors,
                        fontFamily: bF,
                        fontWeight: FontWeight.normal,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(vertical: 5.r, horizontal: 15.r),
            child: Row(
              children: [
                Container(
                  alignment: Alignment.centerLeft,
                  width: 45.r,
                  child: Text(
                    SR.password.tr,
                    style: TextStyle(
                      color: norTextColors,
                      fontSize: customFontSizeCons.r,
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    margin: EdgeInsets.only(left: 15.r),
                    child: TextField(
                      focusNode: state.passwordFocusNode,
                      obscureText: state.isObscure,
                      onChanged: (text) {
                        logic.updatePassword(text);
                      },
                      showCursor: true,
                      cursorColor: norMainThemeColors,
                      controller: state.passwordTextFieldController,
                      decoration: InputDecoration(
                        hintText: SR.pleaseInputPassword.tr,
                        border: InputBorder.none,
                        hintStyle: TextStyle(
                          fontSize: customFontSizeCons.r,
                          fontWeight: FontWeight.normal,
                          fontFamily: bF,
                        ),
                        suffixIcon: IconButton(
                          onPressed: () {
                            logic.updateIsObscure();
                          },
                          icon: Icon(
                            state.isObscure
                                ? Icons.visibility
                                : Icons.visibility_off,
                            size: iconSizeCons.r,
                          ),
                        ),
                      ),
                      style: TextStyle(
                        fontSize: customFontSizeCons.r,
                        color: norTextColors,
                      ),
                    ),
                  ),
                ),
                Container(
                  padding: EdgeInsets.only(left: 20.r),
                  child: Text(
                    SR.forgetPassword.tr,
                    style: TextStyle(
                      color: norMainThemeColors,
                      fontSize: customFontSizeCons.r,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  ///手机号码/验证码
  Widget buildTelAndVerifyCode(BuildContext context) {
    return Container(
      color: norWhite01Color,
      width: 1.sw,
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.symmetric(vertical: 2.r, horizontal: 15.r),
            decoration: BoxDecoration(
              color: norWhite01Color,
              border: Border(
                bottom: BorderSide(width: 2.r, color: norWhite06Color),
              ),
            ),
            child: Row(
              children: [
                Container(
                  alignment: Alignment.centerLeft,
                  width: 40.r,
                  child: Text(
                    state.regionList[state.regionIndex].telNum,
                    style: TextStyle(
                      color: norTextColors,
                      fontSize: customFontSizeCons.r,
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    margin: EdgeInsets.only(left: 15.r),
                    child: TextField(
                      focusNode: state.telFocusNode,
                      autofocus: true,
                      showCursor: true,
                      onChanged: (text) {
                        logic.updateTel(text);
                      },
                      cursorColor: norMainThemeColors,
                      controller: state.telTextEditController,
                      decoration: InputDecoration(
                        hintText: SR.pleaseInputTel.tr,
                        border: InputBorder.none,
                        hintStyle: TextStyle(
                          fontSize: customFontSizeCons.r,
                          fontFamily: bF,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      style: TextStyle(
                        fontSize: customFontSizeCons.r,
                        color: norMainThemeColors,
                        fontFamily: bF,
                        fontWeight: FontWeight.normal,
                      ),
                    ),
                  ),
                ),
                TimerButton(
                  onTap: () async {
                    if (state.telText.isNotEmpty) {
                      await logic.sendSMS();
                    } else {
                      SmartDialog.showToast("嘿，留个电话~");
                    }
                  },
                  isEnable: state.telText.isNotEmpty ? true : false,
                )
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(vertical: 5.r, horizontal: 15.r),
            child: Row(
              children: [
                Container(
                  alignment: Alignment.centerLeft,
                  width: 40.r,
                  child: Text(
                    SR.code.tr,
                    style: TextStyle(
                      color: norTextColors,
                      fontSize: customFontSizeCons.r,
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    margin: EdgeInsets.only(left: 15.r),
                    child: TextField(
                      onChanged: (text) {
                        logic.updateVerifyText(text);
                      },
                      showCursor: true,
                      cursorColor: norMainThemeColors,
                      controller: state.verifyPasswordTextFieldController,
                      decoration: InputDecoration(
                        hintText: SR.pleaseInputCode.tr,
                        border: InputBorder.none,
                        hintStyle: TextStyle(
                          fontSize: customFontSizeCons.r,
                          fontFamily: bF,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      style: TextStyle(
                        fontSize: customFontSizeCons.r,
                        color: norTextColors,
                        fontFamily: bF,
                        fontWeight: FontWeight.normal,
                      ),
                    ),
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  ///选择地区的弹框
  buildRegionDialog() async {
    // List<Widget> widgets = [];
    // for (int i = 0; i < state.regionList.length; i++) {
    //   widgets.add(TextButton(
    //     onPressed: () {
    //       regionIndex = i;
    //       Navigator.pop(context);
    //     },
    //     child: Text(
    //       regionList[i].region,
    //       style: const TextStyle(color: norTextColors),
    //     ),
    //   ));
    // }
    // var regionDialog = await showDialog(
    //   context: context,
    //   builder: (context) {
    //     return SimpleDialog(
    //       title: Text(
    //         SR.zone.tr,
    //         style: TextStyle(
    //             fontSize: 14.sp,
    //             ),
    //       ),
    //       children: widgets,
    //     );
    //   },
    // );
    // return regionDialog;
  }

  Widget buildLoginAgreement() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15.r),
      child: Column(
        children: [
          GestureDetector(
            //checkbox
            onTap: () {
              logic.changeIsAgree();
            },
            child: Text.rich(
              //实现换行
              TextSpan(
                children: [
                  WidgetSpan(
                    child: RectangleCheckBox(
                      //自定义矩形的checkbox
                      size: customFontSizeCons.r,
                      checkedColor: norMainThemeColors,
                      isChecked: state.isAgree,
                      onTap: (value) {
                        logic.changeIsAgree();
                      },
                    ),
                  ),
                  TextSpan(
                    text: "   ",
                    style: TextStyle(fontSize: customFontSizeCons.r),
                  ),
                  TextSpan(
                    text: SR.userAgreementText01.tr,
                    style: TextStyle(
                      color: norGrayColor,
                      fontSize: customFontSizeCons.r,
                    ),
                  ),
                  TextSpan(
                    text: SR.userAgreementText02A.tr,
                    style: TextStyle(
                      color: norBlue01Colors,
                      fontSize: customFontSizeCons.r,
                    ),
                  ),
                  TextSpan(
                    text: SR.userAgreementText03.tr,
                    style: TextStyle(
                      color: norGrayColor,
                      fontSize: customFontSizeCons.r,
                    ),
                  ),
                  TextSpan(
                    text: SR.userAgreementText02B.tr,
                    style: TextStyle(
                      color: norBlue01Colors,
                      fontSize: customFontSizeCons.r,
                    ),
                  ),
                  state.loginTypeIsMessage
                      ? TextSpan(
                          text: SR.userAgreementText05.tr,
                          style: TextStyle(
                            color: norGrayColor,
                            fontSize: customFontSizeCons.r,
                          ),
                        )
                      : const TextSpan(),
                ],
              ),
            ),
          ),
          20.verticalSpace,
          Text.rich(
            TextSpan(
              children: [
                TextSpan(
                  text: SR.havingProblems.tr,
                  style: TextStyle(
                    color: norGrayColor,
                    fontSize: customFontSizeCons.r,
                  ),
                ),
                TextSpan(
                  text: SR.seeTheHelp.tr,
                  style: TextStyle(
                    color: norBlue01Colors,
                    fontSize: customFontSizeCons.r,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  ///验证登录（短信登录的登录按钮）
  Widget buildVerifyLoginButton() {
    return Opacity(
      opacity: state.telText.isNotEmpty && state.verifyText.isNotEmpty ? 1 : .5,
      child: ElevatedButton(
        style: ButtonStyle(
          overlayColor:
              MaterialStateProperty.all(norTextColors.withOpacity(.1)),
          elevation: MaterialStateProperty.all(0),
          backgroundColor: MaterialStateProperty.all(norMainThemeColors),
          minimumSize: MaterialStateProperty.all(Size(200.r, 40.r)),
        ),
        onPressed: state.telText.isNotEmpty && state.verifyText.isNotEmpty
            ? () {
                ///短信验证登录（同时获取登录后的用户基本信息）
                logic.messageVerifyLogin();
              }
            : () {
                SmartDialog.showToast("电话或验证码为空");
              },
        child: Text(
          SR.verifyLogin.tr,
          style: TextStyle(
            color: norWhite01Color,
            fontSize: customFontSizeCons.r,
            fontWeight: FontWeight.normal,
          ),
        ),
      ),
    );
  }

  ///注册登录
  Widget buildRegisterAndLoginButton() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        ElevatedButton(
          style: ButtonStyle(
              overlayColor:
                  MaterialStateProperty.all(norTextColors.withOpacity(.1)),
              elevation: MaterialStateProperty.all(0),
              backgroundColor: MaterialStateProperty.all(norWhite01Color),
              minimumSize: MaterialStateProperty.all(Size(150.r, 40.r)),
              shape: MaterialStateProperty.all(
                RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(3.r)),
                    side: BorderSide(color: norMainThemeColors)),
              )),
          onPressed:
              state.userNameText.isNotEmpty && state.passwordText.isNotEmpty
                  ? () {
                      SmartDialog.showToast("暂无注册功能");
                    }
                  : null,
          child: Text(
            SR.register.tr.toUpperCase(),
            style: TextStyle(
              color: norMainThemeColors,
              fontSize: customFontSizeCons.r,
              fontWeight: FontWeight.normal,
            ),
          ),
        ),
        Opacity(
          opacity:
              state.userNameText.isNotEmpty && state.passwordText.isNotEmpty
                  ? 1
                  : .5,
          child: ElevatedButton(
            style: ButtonStyle(
              overlayColor:
                  MaterialStateProperty.all(norTextColors.withOpacity(.1)),
              elevation: MaterialStateProperty.all(0),
              backgroundColor: MaterialStateProperty.all(norMainThemeColors),
              minimumSize: MaterialStateProperty.all(Size(150.r, 40.r)),
            ),
            onPressed:
                state.userNameText.isNotEmpty && state.passwordText.isNotEmpty
                    ? () {
                        logic.userNameAndPasswordLogin();
                      }
                    : null,
            child: Text(
              SR.login.tr.toUpperCase(),
              style: TextStyle(
                color: norWhite01Color,
                fontSize: customFontSizeCons.r,
                fontWeight: FontWeight.normal,
              ),
            ),
          ),
        ),
      ],
    );
  }
}
